package com.wpf.servlet;

import java.io.IOException;
import java.util.ArrayList;
import com.wpf.bean.Pagebean;
import com.wpf.bean.Userbean;
import com.wpf.dao.UserDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class ShowPage extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public ShowPage() {}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
		HttpSession session = request.getSession();
		Pagebean pagebean = (Pagebean) session.getAttribute("pageresult");
		int dbAllRow = pagebean.getDbAllRow();
		if(dbAllRow>0) {
			StringBuffer queryAllBuffer = new StringBuffer();
			int pageSize = pagebean.getPageSize();
			int pageCount = pagebean.getPageCount();
			int pageNow = 1;
			ArrayList<Userbean> list = pagebean.getRowSet();
			String action = request.getParameter("action");
			int JumpPageNum = 1;
			if(action!=null){
				JumpPageNum = Integer.parseInt(request.getParameter("jumppagenum"));
				pageNow = pagebean.getPageNow();
				switch (action) {
				case "首页":
					pageNow=1;
					break;
				case "上一页":
					if(pageNow>1) pageNow--;
					break;
				case "下一页":
					if(pageCount>pageNow) pageNow++;
					break;
				case "页尾":
					pageNow=pageCount;
					break;
				case "跳转":
					pageNow=JumpPageNum;
					break;
				default:
					break;
				}		
			}
			pagebean.setPageNow(pageNow);
			UserDAO.bufferAppend(queryAllBuffer);
			if(pageCount==1) {
				for(int i=0;i<dbAllRow;i++) {
					UserDAO.bufferAppend(queryAllBuffer,list,i);
				}
			}else if(pageCount>1) {
				int startpage = pageSize*(pageNow-1);
				for(int i=startpage;i<startpage+pageSize && i<dbAllRow;i++) {
					UserDAO.bufferAppend(queryAllBuffer,list,i);
				}
			}
			queryAllBuffer.append("</table>");
			pagebean.setQueryResult(new String(queryAllBuffer));
			session.setAttribute("pageresult", pagebean);
		}
		response.sendRedirect("wpf_index.jsp");
	}

}
